package isquirrel.servlets;

import isquirrel.Logger;
import isquirrel.YouTubeAPI;
import isquirrel.beans.Interest;
import isquirrel.beans.Url;
import isquirrel.beans.User;
import isquirrel.beans.YouTubeVideo;
import isquirrel.error.CannotLoginUserException;
import isquirrel.servlets.handler.HttpDBServlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.json.JSONException;

/**
 * Servlet implementation class Videos
 */
public class Videos extends HttpDBServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Videos() {
        super();
    }

	@Override
	protected void handleGet() throws ServletException, IOException,
			JSONException, CannotLoginUserException {
		
	}

	@Override
	protected void handlePost() throws ServletException, IOException,
			JSONException, CannotLoginUserException {

		User u = getLoggedInUser();
		
		int latest = Integer.valueOf((String)request.getParameter("latest"));
		
		ArrayList<String> keywords = new ArrayList<String>();
		/*
		if (latest > 0){
			int i = 0;
			Iterator<Interest> it = u.getInterests().iterator();
			while (i < 4 ){
				String keyword = "";
				if (Math.random() > 0.6 && u.hasKeywords()) {keyword = u.getKeyword();}
				else {
					int rnd = (int) Math.floor(Math.random() * (u.getInterests().size()));
					if (rnd == 0 ) keyword = it.next().getLabel();
					else{
						while (rnd > 0){
							keyword = it.next().getLabel();
							--rnd;
						}
					}
				}
				System.out.println(keyword);
				keywords.add(keyword);
				it = u.getInterests().iterator();
				++i;
			}	
		}
		else{
		*/
			Iterator<Interest> iterator = u.getInterests().iterator();
			while (iterator.hasNext()){
			
				keywords.add(iterator.next().getLabel());
			
			}
		//}
			
		/* CHANGE: YouTube API now uses the pagination feature to provide a different video set on each 'view more' */
		YouTubeAPI api = new YouTubeAPI();
		Vector<YouTubeVideo> vids = api.getVideosByKeywords(keywords,YouTubeAPI.OR_KEYWORDS, latest);

		if (vids.size() == 0){
			response.getWriter().print("<div>Hmm, that's weird! We found no videos that would be of interest to you. You can try adding more interests.</div>");
		}
		else{
			Logger.log(u, "viewing video recs");
				
			if (request.getParameter("viewmore") != null && ((String)request.getParameter("viewmore")).equals("t")){
				response.getWriter().println("<div id='rec_videos_content_changeable'>");
			}
			
			String style = "style='display:none' ";
			if (latest == 0){
				style = "";
			}
			response.getWriter().println("<div "+ style + "id='rec_videos_page_" + latest+ "'>");
			for (YouTubeVideo vid: vids){
				if (vid == null) continue;
				String vidclass = "'ytvideocontainer'";
				String title = vid.getTitle().replace("'","`");
				if (title.length() > 80){
					title = title.substring(0, 80) + "...";
				}
				int liked = 0;
				if (u.getLikedUrls().contains(new Url(title,"http://www.youtube.com/watch?v=" + vid.getId()))){
					liked = 1;
				};
				response.getWriter().print("<div class=" + vidclass + "><div style='display:none' id='" + vid.getId() + "_liked_locally'>n</div>" +
					     	"<img onMouseOver='window.highlight(this);' onMouseOut='window.unhighlight(this);' onClick=\"player.load(" + liked + ",'" + vid.getId() + "','" + title + "')\" class='videothumb' src='"  + vid.thumbs().get(0) + "' />" +
					     	"<div class='videodetails'>" + 
					       	   "<div class='videotitle'>" +
					   		       title +
					           "</div>" +
					        "</div>" +
					      "</div>");
			}
			response.getWriter().println("</div>"); //close pagelet 
			if (request.getParameter("viewmore") != null && ((String)request.getParameter("viewmore")).equals("t")){
				response.getWriter().print("</div>"); //close content changeable -- this is shown only once
				response.getWriter().print("<div id='videos_viewmore' onClick='window.viewmore(\"Videos\")' class='viewmore clickable'> View more </div>");
			}
		}
	}

}
